<template>
    <div class="p-6 bg-white rounded-lg shadow-md">
        <!-- 试卷基本信息展示 -->
       <div class="flex justify-between mb-6">
            <div class="space-y-2">
                <div class="text-lg font-bold">
                    {{ paperInfo.title }}

                </div>
                <div class="flex  items-center space-x-4 text-gray-400">
                    <span>题量：{{ paperInfo.totalQuestions }}</span>
                    <span>满分：{{ paperInfo.totalScore }}</span>
                </div>
            </div>
            <div class="flex items-center space-x-4">
                <el-button type="info"  link >试卷分析报告</el-button>
                <el-button type="info" link >  
                    <font-awesome-icon :icon="['fas', 'arrow-up-from-bracket']"  class="mr-2" /> 
                    <span>导出答案详情</span>
                </el-button>
                <el-button type="info"  link >  
                    <font-awesome-icon :icon="['fas', 'arrow-up-from-bracket']"  class="mr-2" /> 
                    导出统计详情
                </el-button>
            </div>

       </div>
       <!-- 平均分  -->
       <div class="bg-[#F7FAFC] p-4 rounded-lg flex items-center space-x-6 mb-6">
        <div class="flex items-center space-x-2">
            <span class="font-medium">平均分:</span> <span class="text-[#3A8BFF] cursor-pointer">85.18分</span>
        </div>
        <div class="flex items-center space-x-2">
             <span class="font-medium">平均得分率:</span><span class="text-[#3A8BFF] cursor-pointer">85.18%</span>
        </div>
       </div>
       <!-- 分数分布 -->
        <div  class="mb-6">
            <div class="flex items-center justify-between">
                <div class="flex items-center space-x-2">
                    <span class="font-bold">分数分布</span>
                    <el-tooltip effect="dark" placement="top-start">
                    <template #content>分数自动转换为百分制。未参加考试及<br>待批阅的学生均以0分计算 </template>
                    <el-icon class="text-blue-200 text-lg"><InfoFilled/></el-icon>
                    </el-tooltip>
                </div>
                <el-button type="primary"  link  @click="scoreRangeDialogVisible=true" >  
                 <font-awesome-icon :icon="['fas', 'gear']"  class="mr-2" /> 
                 分数段设置
                </el-button>             
            </div>
             <div ref="scoreChart" class="h-[300px] w-full"></div>
        </div>
       <!-- 题目正确率 -->
        <div  class="mb-6">
           <div class="flex items-center space-x-2">
               <span class="font-bold">题目正确率</span>
           </div>
         
             <div ref="accuracyChart" class="h-[300px] w-full"></div>
        </div>
        <!-- 题目遍历 -->
         <div class="space-y-6" v-for="(section,index1) in questionsInfo" :key="index1">
                <div class="font-bold text-base ">{{section.section_name}}（共 {{section.question_count  }} 题，{{ section.total_score }} 分）</div>
                <div class="space-y-6 px-4" v-for="(question,index2) in section.questions" :key="index2">
                    {{ index2+1 }}.
                    <span class=" text-gray-400">({{question.type}} , {{question.score}}分) </span>
                    <span>{{ question.content }}  </span>
                    <ul class="space-y-3 px-4" v-if="question.type === '单选题' || question.type === '多选题'">
                        <li v-for="(option,index) in question.options" :key="index">{{ option }}</li>
                    </ul>
                   <div class="flex  space-x-2 px-4">
                        <span class="font-semibold whitespace-nowrap">答案:</span>
                        <span v-html="question.answer"></span>
                    </div>
                    <!-- 正确率的统计 -->
                    <div class="bg-[#F7FAFC] p-4 flex justify-between items-center rounded-lg">
                        <div class=" flex justify-between items-center space-x-20 text-sm">
                            <div class="flex items-center space-x-2">
                                <span class="font-semibold">正确率</span>
                                <i class="bg-blue-400 h-3 w-16 rounded-lg"></i>
                                <span>100%</span>
                            </div>
                            <div class="flex items-center space-x-2">
                                <span class="font-semibold">正确:</span>
                                <a class="text-blue-400">38</a>
                                人
                            </div>
                            <div class="flex items-center space-x-2">
                                <span class="font-semibold">错误:</span>
                                <a class="text-blue-400">0</a>
                                人
                            </div>
                            
                        </div>
                        <el-button type="primary" link @click="statisticDetail(question)">
                            <font-awesome-icon :icon="['fas', 'chart-pie']"  class="mr-2" /> 
                            统计详情
                        </el-button>
                    </div>
                </div>     
         </div>

         <!-- 分数段设置的弹框 -->
     <el-dialog v-model="scoreRangeDialogVisible" title="分数段设置"   width="30%" class="rounded-lg">
         <template #header="{ close, titleId, titleClass }">
          <div class="my-header">
            <span :id="titleId" :class="titleClass">
              分数段设置
            </span>    
          </div>
        </template>
        <div class="flex flex-col gap-4 px-6 py-4 i">
            <div class="flex items-center gap-3" v-for="(score,index) in scoreRangeOptions" :key="index">
                <span>分数段{{ index+1 }}</span>
                <el-input class="w-20" v-model.number="score.minScore" @keyup="handleScoreChange('min',index)"/>
                <span v-if="score.minScore==score.maxScore&&score.minScore!=''&&score.maxScore!=''">≤ 学生打分 ≤</span>
                <span v-else>≤ 学生打分 <</span>
                <el-input class="w-20" v-model.number="score.maxScore" @keyup="handleScoreChange('max',index)"></el-input>
                <el-button type="danger" link  @click="deleteRange(score,index)">删除</el-button>
            </div>

        </div>    
        
      <template #footer>
          <div class="px-6 flex items-center justify-between">
            <el-button :icon="Plus" type="primary" link @click="addScoreRange">添加分数段</el-button>
            <div class="flex gap-4">
              <el-button @click="scoreRangeDialogVisible=false" round class="w-20"> 取消 </el-button>
              <el-button type="primary" @click="settingScoreRange" round class="w-20"> 确定 </el-button>
            </div>
          </div>
        </template>

    </el-dialog>
    </div>
</template>

<script setup>
import { ref, watch, onMounted, computed ,reactive} from 'vue'
import { Plus } from '@element-plus/icons-vue'
import * as echarts from 'echarts'
import {getPaperDetail} from '@/api/exam.js'
import { ElMessage,ElMessageBox  } from 'element-plus'
import {useQuestionReviewStore} from '@/store/questionReview'
import { useTabsStore } from '@/store/tabs'
import { useRoute, useRouter } from 'vue-router'
const  questionReviewStore = useQuestionReviewStore()
const  tabsStore = useTabsStore()
const route = useRoute()
const router = useRouter()
// 获取试卷详情数据
const paperInfo = ref({})
// 试卷中的所有题目
const  questionsInfo=ref({})
const fetchData = async () => {
    try {
        await getPaperDetail().then(res =>{
            paperInfo.value = res.data.data.examInfo
            questionsInfo.value = res.data.data.sections
            // console.log(paperInfo.value,'<<<<<<<<<<<<',questionsInfo.value);
        })    
    } catch (error) {
        console.error('获取试卷详情数据失败:', error)
    }
}
onMounted(() => {
    fetchData()
})


const data = [
    { range: '0-60分', proportion: 2.6, count: 31 },
    { range: '60-80分', proportion: 17.9, count: 7 },
    { range: '80-100分', proportion: 79.3, count: 1 },
    { range: '100分', proportion: 0, count: 0 }
];
        
const colors = ['#4CD964', '#FFB673', '#FF7C7C', '#3B7CFF'];

//图表1 
const  scoreChart = ref(null)
let  scoreChartInstance = null
const  scoreChartOptions = reactive({
    tooltip: {
        trigger: 'axis',
        axisPointer: {
            type: 'shadow'
        },
        formatter: function(params) {
            const data = params[0];
            return `${data.name}<br/>百分比: ${data.value}%<br/>人数: ${data.data.count}人`;
        }
    },
    grid: {
        left: '3%',
        right: '12%',
        bottom: '3%',
        containLabel: true
    },
    xAxis: {
        type: 'value',
        max: 100,
        name: '百分比(100%)',
        nameLocation: 'end',
        nameGap: 10,
        nameTextStyle: {
            color: '#666',
            fontSize: 14,
            padding: [0, 0, -30, 0]
        },
        axisLabel: {
            formatter: '{value}%'
        },
        splitLine: {
            lineStyle: {
                type: 'dashed',
                color: '#e0e0e0'
            }
        }
    },
    yAxis: {
        type: 'category',
        data: data.map(item => item.range),
        axisLine: {
            lineStyle: {
                color: '#e0e0e0'
            }
        },
        axisLabel: {
            fontSize: 14,
            margin: 10
        }
    },
    series: [{
        name: '百分比（100%）',
        type: 'bar',
        data: data.map((item, index) => {
            return {
                value: item.proportion,
                count: item.count,
                itemStyle: {
                    color: colors[index]
                }
            };
        }),
        label: {
            show: true,
            position: 'right',
            formatter: function(params) {
                return `${params.value}% (${params.data.count}人)`;
            },
            fontSize: 14,
            fontWeight: 'bold',
            color: '#A8A8B3'
        },
        barWidth: '30%',
        itemStyle: {
            color: function(params) {
                return colors[params.dataIndex];
            },
            // borderRadius: [0, 6, 6, 0],
            shadowBlur: 4,
            shadowColor: 'rgba(0, 0, 0, 0.2)'
        },
        emphasis: {
            itemStyle: {
                shadowBlur: 12,
                shadowColor: 'rgba(0, 0, 0, 0.3)'
            }
        }
    }],
    animationDuration: 1500,
    animationEasing: 'quarticInOut'
})

// 初始化图表1
const initScoreChart = () => {
  scoreChartInstance = echarts.init(scoreChart.value)
  scoreChartInstance.setOption(scoreChartOptions)
}
//图表2
// 数据准备
const questionNumbers = [1,2,3,4,5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16,18,19,20,21,22,23,24,25];
const accuracyRates = [100, 100, 100, 100, 100, 100, 100,100,92.1, 97.4, 100, 92.1, 89.5, 100,100,100,100,92.1, 97.4, 100, 92.1, 89.5, 100,100,100];
const  accuracyChart = ref(null)
let accuracyChartInstance = null
const  accuracyChartOptions = reactive({
    tooltip: {
        trigger: 'axis',
        axisPointer: {
            type: 'shadow'
        },
        formatter: function(params) {
            return `题目 ${params[0].name}: ${params[0].value}% 正确率`;
        }
    },
    grid: {
        left: '5%',
        right: '5%',
        bottom: '15%',
        top: '10%',
        containLabel: true
    },
    xAxis: {
        type: 'category',
        data: questionNumbers,
        axisLabel: {
            fontSize: 12,
            color: '#A8A8B3'
        },
        axisLine: {
            lineStyle: {
                color: '#ddd'
            }
        },
        name: '题目编号',
        nameLocation: 'end',
        nameTextStyle: {
            padding: [10, 0, 0, 0],
            fontSize: 13,
            fontWeight: 'bold'
        }
    },
    yAxis: {
        type: 'value',
        min: 0,
        max: 100,
        axisLabel: {
            formatter: '{value}%',
            fontSize: 12,
            color: '#A8A8B3'
        },
        splitLine: {
            lineStyle: {
                type: 'dashed',
                color: '#eaecef'
            }
        },
        name: '正确率/得分率(%)',
        nameLocation: 'center',
        nameRotate: 90,
        nameTextStyle: {
            padding: [0, 0, 40, 200],
            fontSize: 13,
            // fontWeight: 'bold',
            color: '#A8A8B3'
        }
    },
    dataZoom: [
        {
            type: 'inside',
            start: 0,
            end: 60
        },
        {
            type: 'slider',
            bottom: '10%',
            start: 0,
            end: 60,
            height: 16,
            borderColor: 'transparent',
            fillerColor: 'rgba(52, 152, 219, 0.3)',
            backgroundColor: '#eaecef',
            handleStyle: {
                color: '#3498db'
            },
            textStyle: {
                color: '#7f8c8d'
            }
        }
    ],
    series: [
        {
            name: '正确率',
            type: 'bar',
            data: accuracyRates.map((value, index) => {
                return {
                    value: value,
                    itemStyle: {
                        color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
                            { offset: 0, color: '#7DD9AE' },
                            { offset: 1, color: '#62D4AA' }
                        ])
                    }
                };
            }),
            barWidth: '30%',
            label: {
                show: true,
                position: 'top',
                formatter: '{c}%',
                color: '#A8A8B3',
                fontSize: 12,
                fontWeight: 'bold'
            },
            itemStyle: {
                borderRadius: [4, 4, 0, 0],
                shadowColor: 'rgba(0, 0, 0, 0.1)',
                shadowBlur: 5,
                shadowOffsetY: 2
            },
            emphasis: {
                itemStyle: {
                    shadowColor: 'rgba(0, 0, 0, 0.2)',
                    shadowBlur: 8,
                    shadowOffsetY: 4
                }
            }
        }
    ],
    animationDuration: 1500,
    animationEasing: 'cubicOut'
 })
const initAccuracyChart = () => { 
    accuracyChartInstance = echarts.init(accuracyChart.value)
    accuracyChartInstance.setOption(accuracyChartOptions)
}

onMounted(()=>{
  initScoreChart()
  initAccuracyChart()
   window.addEventListener('resize', () => {
    scoreChartInstance?.resize();
    accuracyChartInstance?.resize();
  });
})

//分数段设置的弹出框
const  scoreRangeDialogVisible = ref(false)
//设置分数段
const  scoreRangeOptions = reactive([
    { id: 1, minScore: 100, maxScore: 100 },
    { id: 2, minScore: 80, maxScore: 100 },
    { id: 3, minScore:60, maxScore: 80 },
    { id: 4, minScore: 0, maxScore: 60,}
])
//添加分数段
const  addScoreRange = ()=>{
    console.log('添加分数段');
    scoreRangeOptions.push({ id: scoreRangeOptions.length + 1, minScore: '', maxScore: '' })
}
//删除分数段
const  deleteRange = (score,index)=>{
    console.log('删除分数段');
    scoreRangeOptions.splice(index, 1)
}
// 输入分数段的验证 
const  handleScoreChange= (type,index)=>{
    console.log('输入分数段的验证',type,index);
    if(type === 'min'){
        if(scoreRangeOptions[index].minScore<0 || scoreRangeOptions[index].minScore>=100){
            scoreRangeOptions[index].minScore = ''
            ElMessage.error('请输入0~100的整数')
        }
    }else if(type === 'max'){
        if(scoreRangeOptions[index].maxScore<0 || scoreRangeOptions[index].maxScore>=100){
            scoreRangeOptions[index].maxScore = ''
            ElMessage.error('请输入0~100的整数')
        } 
    }
}
const  settingScoreRange = ()=>{
    console.log('设置分数段'); 
    // 判断添加的分数段是合法
    // 验证所有分数段是否合法
    for (let i = 0; i < scoreRangeOptions.length; i++) {
        const current = scoreRangeOptions[i];
        
        // 检查是否为空
        if (current.minScore === '' || current.maxScore === '') {
            ElMessage.error(`第 ${i + 1} 个分数段不能为空`);
            return;
        }
        
        // 检查是否为数字
        if (isNaN(current.minScore) || isNaN(current.maxScore)) {
            ElMessage.error(`第 ${i + 1} 个分数段必须为数字`);
            return;
        }
        
        // 转换为数字类型
        const min = Number(current.minScore);
        const max = Number(current.maxScore);
        
        // 检查范围是否合法
        if (min < 0 || max > 100) {
            ElMessage.error(`第 ${i + 1} 个分数段必须在 0-100 范围内`);
            return;
        }
        
        // 检查最小分数是否大于最大分数
        if (min > max) {
            ElMessage.error(`第 ${i + 1} 个分数段的最小分数不能大于最大分数`);
            return;
        }
        
        // 检查与上一个分数段的关系（从第二个分数段开始检查）
        if (i > 0) {
            const prev = scoreRangeOptions[i - 1];
            const prevMin = Number(prev.minScore);
            
            if (max > prevMin) {
                ElMessage.error(`第 ${i + 1} 个分数段的最大分数不能大于前一个分数段的最小分数`);
                return;
            }
        }
    }

    scoreRangeDialogVisible.value = true
}

//统计详情
const statisticDetail=(question)=>{
    console.log(question.id);
     tabsStore.addTab({
      name: 'DetailedStatistics',
      title: '详情统计',
    });

    questionReviewStore.paperId = paperInfo.value.id
    questionReviewStore.questionId = question.id
    router.push({name:'DetailedStatistics',params:{paperId:paperInfo.value.id,questionId:question.id}})


}
</script >
<style lang="less" scoped>
</style>